package com.mworld.galaxy.bull.service.product;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.mworld.galaxy.bull.entity.product.ProductImage;
import com.mworld.galaxy.bull.repository.product.ProductImageDao;

@Component
@Transactional(readOnly = true)
public class ProductImageService {

    @Autowired
    private ProductImageDao productImageDao;

    public ProductImage getProductImage(Long id) {
        return productImageDao.findOne(id);
    }

    public ProductImage getProductImage(String id) {
        try {
            return getProductImage(Long.parseLong(id));
        } catch (Exception err) {
            return null;
        }
    }

    public Page<ProductImage> searchProductImage(Long productId) {
        PageRequest pageRequest = new PageRequest(0, 100, new Sort(Direction.DESC, "order"));
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("product.id", new SearchFilter("product.id", Operator.EQ, productId));
        Specification<ProductImage> spec = DynamicSpecifications.bySearchFilter(filters.values(), ProductImage.class);
        return productImageDao.findAll(spec, pageRequest);
    }

    @Transactional(readOnly = false)
    public void saveProductImage(ProductImage productImageId) {
        productImageDao.save(productImageId);
    }

    @Transactional(readOnly = false)
    public void deleteProductImage(Long productImageId) {
        productImageDao.delete(productImageId);
    }
}
